const App = getApp();
// 记录规格的数组
let goodsSpecArr = [];
const util = require('../../utils/util.js');
// 富文本插件
const wxParse = require("../../wxParse/wxParse.js");
Page({

  data: {
    goods_num: 1, // 商品数量
    goods_sku_id: 0, // 规格id
    goodsMultiSpec: {}, // 多规格信息
    indexAD:"",
    indexAdArr:[],
    // 页面参数
    options: {},
    // 页面元素
    items: {},
    showBottomPopup:false,
    scrollTop: 0,
    kefuImg:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let arr = [
      {path:App.YU+'/assets/ad1.png', name:'STEP1', name2:'线上私信'},
      {path:App.YU+'/assets/ad2.png', name:'STEP2', name2:'线上下单'},
      {path:App.YU+'/assets/ad3.png', name:'STEP3', name2:'预约面诊'},
      {path:App.YU+'/assets/ad4.png', name:'STEP4', name2:'到院体验'},
      {path:App.YU+'/assets/ad5.png', name:'STEP5', name2:'客服回访'}
    ];
    this.setData({indexAD:App.YU+'/assets/indexAD.jpg', indexAdArr:arr, kefuImg:App.YU+'/assets/ad3.png'})
    // 当前页面参数
    this.setData({
      options
    });
    // 加载页面数据
    this.getPageData();
    //TEST
    //wx.navigateTo({  url: '/pages/promotion/activity?pid=3' })

    // console.log(App.globalData.navbar);
  },
onShow(){
//   App.pageOnLoad(this);
  //设置tabbar购物车总数量
  App.setBuyCarNumFun()
},
  /**
   * 加载页面数据
   */
  getPageData(callback) {
    let _this = this;
    App._get('page/index', {
      page_id: _this.data.options.page_id || 0
    }, result => {
      // 设置顶部导航栏栏
      _this.setPageBar(result.data.page);
      _this.setData(result.data);	//这其中就包含了,itms属性
    //   console.log('init index', result.data)
      // 回调函数
      typeof callback === 'function' && callback();
    });
  },

  /**
   * 设置顶部导航栏
   */
  setPageBar(page) {
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: page.params.title
    });
    // 设置navbar标题、颜色
    wx.setNavigationBarColor({
      frontColor: page.style.titleTextColor === 'white' ? '#ffffff' : '#000000',
      backgroundColor: page.style.titleBackgroundColor
    })
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    // 获取首页数据
    this.getPageData(function () {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    const _this = this;
    return {
      title: _this.data.page.params.share_title,
      path: "/pages/index/index?" + App.getShareUrlParams()
    };
  },
  //预览商品缩略图
  onPreviewSkuImage(e) {
    let _this = this;
    let img = e.currentTarget.dataset.img;
    wx.previewImage({
      current: img,
      urls: [img]
    })
  },
  /**
   * 分享到朋友圈
   * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
   * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
   */
  onShareTimeline() {
    const _this = this;
    return {
      title: _this.data.page.params.share_title,
      path: "/pages/index/index?" + App.getShareUrlParams()
    };
  },

  //商品组件中的 组件中点击的事件 传递到顶层
  onMyEvent00(e){
    let _this = this;
    console.log('组件传递过来的数据00000', e)
    let goodid = e.detail.goodid
    this.setData({showBottomPopup:true,goods_id:goodid,goods_num:1,goods_sku_id:0,goodsMultiSpec:{}})
    // 请求单条商品信息
    App._get('goods/detail', {
      goods_id: goodid
    }, (result) => {
      // 初始化商品详情数据
      let data = _this._initGoodsDetailData(result.data);
      // console.log(111,data.cart_total_num)
      // 设置tabbar购物车总数量
      App.setBuyCarNum(result.data.cart_total_num)
      _this.setData(data);
    });
  },
  //关闭顶层弹出层
  onClosePopup(){
    this.setData({showBottomPopup:false})
  },
  _initGoodsDetailData(data) {
    let _this = this;
    // 商品详情
    let goodsDetail = data.detail;
    // 富文本转码
    if (goodsDetail.content.length > 0) {
      wxParse.wxParse('content', 'html', goodsDetail.content, _this, 0);
    }
    // 商品价格/划线价/库存
    data.goods_sku_id = goodsDetail.goods_sku.spec_sku_id;
    data.goods_price = goodsDetail.goods_sku.goods_price;
    data.line_price = goodsDetail.goods_sku.line_price;
    data.stock_num = goodsDetail.goods_sku.stock_num;
    // 商品封面图(确认弹窗)
    data.skuCoverImage = goodsDetail.goods_image;
    // 多规格商品封面图(确认弹窗)
    if (goodsDetail.spec_type == 20 && goodsDetail.goods_sku['image']) {
      data.skuCoverImage = goodsDetail.goods_sku['image']['file_path'];
    }
    // 初始化商品多规格
    if (goodsDetail.spec_type == 20) {
      data.goodsMultiSpec = _this._initManySpecData(goodsDetail.goods_multi_spec);
    }
    return data;
  },
  //初始化多规格商品
  _initManySpecData(data) {
    goodsSpecArr = [];
    for (let i in data.spec_attr) {
      for (let j in data.spec_attr[i].spec_items) {
        if (j < 1) {
          data.spec_attr[i].spec_items[0].checked = true;
          goodsSpecArr[i] = data.spec_attr[i].spec_items[0].item_id;
        }
      }
    }
    return data;
  },
  //点击切换不同商品规格
  onSwitchSpec(e) {
    let _this = this,
      attrIdx = e.currentTarget.dataset.attrIdx,
      itemIdx = e.currentTarget.dataset.itemIdx,
      goodsMultiSpec = _this.data.goodsMultiSpec;
    for (let i in goodsMultiSpec.spec_attr) {
      for (let j in goodsMultiSpec.spec_attr[i].spec_items) {
        if (attrIdx == i) {
          goodsMultiSpec.spec_attr[i].spec_items[j].checked = false;
          if (itemIdx == j) {
            goodsMultiSpec.spec_attr[i].spec_items[itemIdx].checked = true;
            goodsSpecArr[i] = goodsMultiSpec.spec_attr[i].spec_items[itemIdx].item_id;
          }
        }
      }
    }
    _this.setData({
      goodsMultiSpec
    });
    // 更新商品规格信息
    _this._updateSpecGoods();
  },
  //更新商品信息
  _updateSpecGoods() {
    let _this = this,
      specSkuId = goodsSpecArr.join('_');
    // 查找skuItem
    let spec_list = _this.data.goodsMultiSpec.spec_list,
      skuItem = spec_list.find((val) => {
        return val.spec_sku_id == specSkuId;
      });
    // 记录goods_sku_id
    // 更新商品价格、划线价、库存
    if (typeof skuItem === 'object') {
      _this.setData({
        goods_sku_id: skuItem.spec_sku_id,
        goods_price: skuItem.form.goods_price,
        line_price: skuItem.form.line_price,
        stock_num: skuItem.form.stock_num,
        skuCoverImage: skuItem.form.image_id > 0 ? skuItem.form.image_path : _this.data.detail.goods_image
      });
    }
  },
  //增加商品数量
  onIncGoodsNumber(e) {
    let _this = this;
    App.saveFormId(e.detail.formId);
    _this.setData({
      goods_num: ++_this.data.goods_num
    })
  },
  //减少商品数量
  onDecGoodsNumber(e) {
    let _this = this;
    App.saveFormId(e.detail.formId);
    if (_this.data.goods_num > 1) {
      _this.setData({
        goods_num: --_this.data.goods_num
      });
    }
  },
  //自定义输入商品数量
  onInputGoodsNum(e) {
    let _this = this,
      iptValue = e.detail.value;
    if (!util.isPositiveInteger(iptValue) && iptValue !== '') {
      iptValue = 1;
    }
    _this.setData({
      goods_num: iptValue
    });
  },
  //加入购物车或立即购买
  onConfirmSubmit(e) {
    let _this = this,
      submitType = e.currentTarget.dataset.type;
    if (submitType === 'buyNow') {
      // 立即购买
      wx.navigateTo({
        url: '../flow/checkout?' + util.urlEncode({
          order_type: 'buyNow',
          goods_id: _this.data.goods_id,
          goods_num: _this.data.goods_num,
          goods_sku_id: _this.data.goods_sku_id,
        }),
        success() {
          // 关闭弹窗
          _this.onClosePopup()
        }
      });
      this.onClosePopup()
    } else if (submitType === 'addCart') {
      // 加入购物车
      App._post_form('cart/add', {
        goods_id: _this.data.goods_id,
        goods_num: _this.data.goods_num,
        goods_sku_id: _this.data.goods_sku_id,
      }, (result) => {
        App.showSuccess(result.msg);
        // 其中返回购物车总数量cart_total_num
        _this.setData(result.data);
        // 关闭购物车
        _this.onClosePopup();
        // console.log(222,result.data.cart_total_num)
        // 设置tabbar购物车总数量缓存
        App.setBuyCarNum(result.data.cart_total_num)
        //设置tabbar购物车总数量
        App.setBuyCarNumFun()
      });
    }
  },
});